import {GameMain} from "./GameMain";


export default class WXUser
{
    public openId:string="";
    public userInfoSetted:boolean=false;
    public userName:string="";
    public avatarUrl:string="";

    public city:string="未定位";


    public static readonly getOpenIdUrl:string="https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

    public setCity(city:string)
    {
        this.city=city;
    }

    public isCitySetted():boolean
    {
        return this.city!=="未定位";
    }

    public setUserInfo(userInfo)
    {
        if(!userInfo)
            return;
        this.userInfoSetted=true;
        this.userName=userInfo.nickName;
        this.avatarUrl=userInfo.avatarUrl;

        GameMain.instance.updateWXUserInfo(userInfo);
    }

    public getUserInfo()
    {
        wx.getUserInfo({
            success:(res)=>{
                //console.log("** getUserInfo成功="+JSON.stringify(res.userInfo));
                this.setUserInfo(res.userInfo);
            },
            fail:(err)=>{
                wx.getUserProfile({
                    desc:"用于参与世界排行榜排名",
                    success:(res)=>{
                        //console.log("** getUserProfile授权成功="+JSON.stringify(res.userInfo));
                        this.setUserInfo(res.userInfo);
                    },
                    fail:(err)=>{
                        //console.log("*** getUserProfile授权失败");
                    }
                });
            }
        });
    }

    public getOpenId()
    {
        wx.cloud.callFunction({
            name:"add",
            data:{
                a:5,
                b:4
            },
            success:(res)=>{
                console.log("**  云函数调用成功="+res.result.sum+"  openId="+res.result.openid+"   appid="+res.result.appid);
                this.openId=res.result.openid;

                //尝试添加一条用户记录
                GameMain.instance.addWXCloudRecord(this.openId);
            },
            fail:(res)=>{

            }
        });
    }

    public isOpenIdGetted():boolean
    {
        return this.openId!=="" && this.openId.length>0;
    }
}

